package com.lunesu.bjair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class BeijingAirActivity extends Activity {
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.main);

		// NO: we use a theme in the manifest, which will also work during startup
//		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// NO: webbrowser would show address bar
		//startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://iphone.bjair.info/")));
		
		WebView webview = (WebView)this.findViewById(R.id.webview1);
		webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		// the 'details' button uses javascript
		webview.getSettings().setJavaScriptEnabled(true);
		webview.setBackgroundColor(android.R.color.black);

		if (savedInstanceState == null || !savedInstanceState.containsKey(cacheKey)) {
			//webview.loadUrl("file:///android_asset/hello.html");
			refresh();
		}
		else {
			// TODO: load from cache
			// NO: would try to load images/css also from cache
			//webview.loadUrl("content://com.lunesu/cache.html");
			setWebviewContent(cache = savedInstanceState.getString(cacheKey));
		}

		// onStart will be called next
	}

	static final String cacheKey = "cache";
	
	String cache;
	
	@Override
	public void onSaveInstanceState(Bundle bundle) {
		super.onSaveInstanceState(bundle);
		if (cache != null)
			bundle.putString(cacheKey, cache);
	}
	
	private static final int MENU_REFRESH = 1;
	
	/* Creates the menu items */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(0, MENU_REFRESH, 0, getString(R.string.refresh))
	    	.setIcon(R.drawable.ic_menu_refresh);
	    return true;
	}

	/* Handles item selections */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case MENU_REFRESH:
	        refresh();
	        return true;
	    }
	    return false;
	}
	
//	@Override
//	public void onStart() {
//		super.onStart();
//		refresh();
//	}
		
	private void refresh() { 
		final Handler handler = new Handler();
		final String baseurl = getString(R.string.bjair_url);
		// HACK: preallocate enough space for the bjair page
		final StringBuilder sb = new StringBuilder(2500);
		
		// TODO: if there's still a thread active, we can leverage its results, 
		// instead of starting another thread here.
		
		final DialogInterface.OnCancelListener cancel = new DialogInterface.OnCancelListener() {			
			@Override
			public void onCancel(DialogInterface dialog) {
				// Close the activity.
				finish();
			}
		};

		final ProgressDialog dialog = ProgressDialog.show(this, "", 
				getString(R.string.updating), true, true, cancel);
				
		// This 'delegate' will be invoked when the thread is done
		final Runnable runInUI = new Runnable() {
			@Override 
			public void run() { 
				// Don't do the updating if we've been canceled (finished)
				if (isFinishing())
				{
					// TODO: write to cache?
					return;
				}
				// set the HTML content in the webview
				// HACK: prevent auto http refresh
				int refresh = sb.indexOf("http-equiv=\"refresh\"");
				if (refresh > 0)
					sb.setCharAt(refresh+13, 'x');	// mangle
				// HACK: replace paypal button ID
				int paypal = sb.indexOf("CK5D4K33FL6KN");
				if (paypal > 0)
					sb.replace(paypal, paypal+13, "99JMDQLEBRA6S");
				// HACK: add some paypal settings in the payment form
				paypal = sb.indexOf("</form>");
				if (paypal > 0)
					sb.insert(paypal, 
							"<input type=\"hidden\" name=\"currency_code\" value=\"EUR\" />"+
							"<input type=\"hidden\" name=\"lc\" value=\"US\" />");
				setWebviewContent(sb.toString());
				dialog.dismiss();
			}
		};

		// Create a thread to update the AQI, and start it.
		new Thread() {
			@Override
			public void run() {
				// Get the air quality from HTTP and record the entire page into a string
				int airquality = BeijingAirAppWidgetProvider.getAirQuality(baseurl, sb);
				// Execute the 'delegate' in the UI thread, so it can update the webview
				handler.post(runInUI);
				// Update the app-widget (apparently this works fine from this thread)
				BeijingAirAppWidgetProvider.updateWidget(BeijingAirActivity.this, airquality);
			}
		}.start();
	}

	/** Show the specified HTML data in the webview.
	 * @param data the HTML data to show in the webview
	 */
	private void setWebviewContent(String data) {
		WebView webview = (WebView)findViewById(R.id.webview1);
		if (data.length() > 0) {
			String baseurl = getString(R.string.bjair_url);
			// TODO: get mimetype/encoding from http
			webview.loadDataWithBaseURL(baseurl, data, null, null, null);
			cache = data;
			
//			FileOutputStream fos;
//			try {
//				fos = this.openFileOutput("cache.html", MODE_PRIVATE);
//				try {
//					fos.write(data.getBytes());
//					fos.flush();
//				}
//				finally {
//					fos.close();
//				}
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//			}
		}
		else {
			// An error occured; show an error message
			webview.loadUrl("file:///android_asset/error.html");
		}
	}	
		
}
